package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.bo.ErpProductUnifiedTakedownBo;
import com.erp.gather.domain.vo.ErpProductUnifiedTakedownVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IAeProductService;
import com.erp.gather.service.IErpProductUnifiedTakedownService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * erp产品统一下架Service业务层处理
 *
 * @author erp
 * @date 2023-06-01
 */
@RequiredArgsConstructor
@Service
public class ErpProductUnifiedTakedownServiceImpl implements IErpProductUnifiedTakedownService {

    private final ErpProductUnifiedTakedownMapper baseMapper;
    private final ErpCollectProductMapper erpCollectProductMapper;
    private final ErpCollectProductExpandMapper erpCollectProductExpandMapper;
    private final ErpSellerProductMapper erpSellerProductMapper;
    private final ErpSellerProductExpandMapper erpSellerProductExpandMapper;
    private final ErpSellerProductSkuMapper erpSellerProductSkuMapper;
    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;
    private final ErpSellerStoreProductExpandMapper erpSellerStoreProductExpandMapper;
    private final IAeProductService aeProductService;

    /**
     * 查询erp产品统一下架
     */
    @Override
    public ErpProductUnifiedTakedownVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询erp产品统一下架列表
     */
    @Override
    public TableDataInfo<ErpProductUnifiedTakedownVo> queryPageList(ErpProductUnifiedTakedownBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpProductUnifiedTakedown> lqw = buildQueryWrapper(bo);
        Page<ErpProductUnifiedTakedownVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询erp产品统一下架列表
     */
    @Override
    public List<ErpProductUnifiedTakedownVo> queryList(ErpProductUnifiedTakedownBo bo) {
        LambdaQueryWrapper<ErpProductUnifiedTakedown> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpProductUnifiedTakedown> buildQueryWrapper(ErpProductUnifiedTakedownBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpProductUnifiedTakedown> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTakedownReason()), ErpProductUnifiedTakedown::getTakedownReason, bo.getTakedownReason());
        lqw.eq(bo.getCollectProductId() != null, ErpProductUnifiedTakedown::getCollectProductId, bo.getCollectProductId());
        lqw.eq(bo.getAeProductId() != null, ErpProductUnifiedTakedown::getAeProductId, bo.getAeProductId());
        lqw.eq(bo.getIsEffective() != null, ErpProductUnifiedTakedown::getIsEffective, bo.getIsEffective());
        lqw.eq(bo.getIsExecute() != null, ErpProductUnifiedTakedown::getIsExecute, bo.getIsExecute());
        lqw.eq(bo.getType() != null, ErpProductUnifiedTakedown::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpProductUnifiedTakedown::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增erp产品统一下架
     */
    @Override
    public Boolean insertByBo(ErpProductUnifiedTakedownBo bo) {
        ErpProductUnifiedTakedown add = BeanUtil.toBean(bo, ErpProductUnifiedTakedown.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改erp产品统一下架
     */
    @Override
    public Boolean updateByBo(ErpProductUnifiedTakedownBo bo) {
        ErpProductUnifiedTakedown update = BeanUtil.toBean(bo, ErpProductUnifiedTakedown.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpProductUnifiedTakedown entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除erp产品统一下架
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<String> setProductTakedown(String takedownReason, Long collectProductId) {

        //先查看是否该商品已经被添加过
        ErpProductUnifiedTakedown erpProductUnifiedTakedown = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpProductUnifiedTakedown>().eq(ErpProductUnifiedTakedown::getCollectProductId, collectProductId)
        );
        if (erpProductUnifiedTakedown != null) {
            return R.fail("该商品已被添加至下架表中，下架原因为" + erpProductUnifiedTakedown.getTakedownReason());
        }
        //如果不存在，插入
        erpProductUnifiedTakedown = new ErpProductUnifiedTakedown();
        erpProductUnifiedTakedown.setTakedownReason(takedownReason);
        erpProductUnifiedTakedown.setCollectProductId(collectProductId);
        erpProductUnifiedTakedown.setIsExecute(0);
        erpProductUnifiedTakedown.setIsEffective(0);
        if (baseMapper.insert(erpProductUnifiedTakedown) > 0) {
            return R.ok("添加成功");
        } else {
            return R.fail("添加失败");
        }
    }

    /**
     * 修复下架
     *
     * @param collectProductId
     * @return
     */
    @Override
    public R<String> repairProductTakedown(Long collectProductId) {
        //根据传入的公共产品id，查看有无记录
        ErpProductUnifiedTakedown erpProductUnifiedTakedown = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpProductUnifiedTakedown>()
                        .eq(ErpProductUnifiedTakedown::getCollectProductId, collectProductId)
                        .eq(ErpProductUnifiedTakedown::getIsEffective, 1).last("limit 1")
        );
        if (erpProductUnifiedTakedown == null) {
            return R.fail("没有需要修复的记录");
        }
        //有该记录的情况，将生效改为不生效即可
        erpProductUnifiedTakedown.setIsEffective(0);
        if (baseMapper.updateById(erpProductUnifiedTakedown) > 0) {
            return R.ok("已修复");
        } else {
            return R.fail("修复异常");
        }
    }

    /**
     * 执行
     */
    @Override
    @Transactional
    public R<String> executeProductTakedown(Long takedownId) {
        ErpProductUnifiedTakedown bo = baseMapper.selectById(takedownId);
        if (bo == null) {
            return R.fail("该计划不存在");
        }
        Integer type = bo.getType();
        //1、获取到公共产品库商品，执行操作为 ： 下架
        ErpCollectProductExpand collectProductExpand = erpCollectProductExpandMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getCollectProductId, bo.getCollectProductId())
        );
        if (collectProductExpand != null) {
            collectProductExpand.setProductStatus(0);
            erpCollectProductExpandMapper.updateById(collectProductExpand);
            //2、获取到个人产品库商品，执行操作为 ： 删除
            List<ErpSellerProduct> erpSellerProductList = erpSellerProductMapper.selectList(
                    new LambdaQueryWrapper<ErpSellerProduct>().eq(ErpSellerProduct::getCollectProductId, bo.getCollectProductId())
            );
            Long sellerProductId = null;
            ErpSellerProductExpand erpSellerProductExpand = new ErpSellerProductExpand();
            List<ErpSellerProductSku> sellerProductSkuList = new ArrayList<>();
            for (ErpSellerProduct sellerProduct : erpSellerProductList) {
                sellerProductId = sellerProduct.getId();
                //删除sku表
                sellerProductSkuList = erpSellerProductSkuMapper.selectList(
                        new LambdaQueryWrapper<ErpSellerProductSku>().eq(ErpSellerProductSku::getSellerProductId, sellerProductId)
                );
                erpSellerProductSkuMapper.deleteBatchIds(sellerProductSkuList);
                erpSellerProductMapper.deleteById(sellerProduct);
                //删除延伸表
                erpSellerProductExpand = erpSellerProductExpandMapper.selectOne(
                        new LambdaQueryWrapper<ErpSellerProductExpand>().eq(ErpSellerProductExpand::getSellerProductId, sellerProductId)
                );
                erpSellerProductExpandMapper.deleteById(erpSellerProductExpand);
            }

            // TODO 暂不删除待用内部类接口 删除自动上架的临时表
            Long collectProductId = collectProductExpand.getCollectProductId();
//            autoCollectProductTemporaryMapper.delete(new LambdaQueryWrapper<ErpAutoCollectProductTemporary>()
//                    .eq(ErpAutoCollectProductTemporary::getCollectProductId,collectProductId));
        }
        //3、获取到在线商品库商品，执行操作为 ： Erp内改变状态，速卖通下架+删除
        List<ErpSellerStoreProduct> erpSellerStoreProductList = erpSellerStoreProductMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreProduct>().eq(ErpSellerStoreProduct::getCollectProductId, bo.getCollectProductId())
        );
        Long sellerStoreProductId = null;
        ErpSellerStoreProductExpand erpSellerStoreProductExpand = new ErpSellerStoreProductExpand();
        List<ErpSellerStoreProductSku> sellerStoreProductSkuList = new ArrayList<>();
        for (ErpSellerStoreProduct sellerStoreProduct : erpSellerStoreProductList) {
            sellerStoreProductId = sellerStoreProduct.getId();
            //修改状态
            erpSellerStoreProductExpand = erpSellerStoreProductExpandMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStoreProductExpand>().eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreProductId)
            );
            erpSellerStoreProductExpand.setProductStatusType("5");
            erpSellerStoreProductExpandMapper.updateById(erpSellerStoreProductExpand);
//            erpSellerStoreProductExpandMapper.deleteById(erpSellerStoreProductExpand);
//            //删除sku表
//            sellerStoreProductSkuList = erpSellerStoreProductSkuMapper.selectList(
//                    new LambdaQueryWrapper<ErpSellerStoreProductSku>().eq(ErpSellerStoreProductSku::getSellerStoreProductId, sellerStoreProductId)
//            );
//            erpSellerStoreProductSkuMapper.deleteBatchIds(sellerStoreProductSkuList);
            // 7、下架产品Long sellerStoreProductIds, Long sellerId, Integer type
            if (sellerStoreProduct.getAeProductId() != null) {
                // 8、删除产品
                //下架速卖通商品
                R<Object> objectR = aeProductService.productOfflineForUpdateTest(sellerStoreProduct.getAeProductId().toString(), sellerStoreProduct.getStoreId(), 0);
                if (objectR.getCode() == 200){
                    //执行下架时，下架失败
                    erpSellerStoreProductExpand.setProductStatusType("6");
                    erpSellerStoreProductExpandMapper.updateById(erpSellerStoreProductExpand);
                }
                //删除速卖通商品
                R<Object> objectR1 = aeProductService.deleteProductToAe(sellerStoreProduct.getAeProductId(), sellerStoreProduct.getStoreId());
                if (objectR1.getCode() != 200){
                    //执行下架时，删除失败
                    erpSellerStoreProductExpand.setProductStatusType("7");
                    erpSellerStoreProductExpandMapper.updateById(erpSellerStoreProductExpand);
                }
            }

        }
        bo.setIsEffective(1);
        bo.setIsExecute(1);
        if (baseMapper.updateById(bo) > 0) {
            return R.ok("执行成功");
        } else {
            return R.fail("执行失败");
        }
    }

    @Override
    public R<Object> getProductUnifiedTakedownListInfo(ErpProductUnifiedTakedown erpProductUnifiedTakedown) {
        LambdaQueryWrapper<ErpProductUnifiedTakedown> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(erpProductUnifiedTakedown.getTakedownReason()), ErpProductUnifiedTakedown::getTakedownReason, erpProductUnifiedTakedown.getTakedownReason());
        lqw.eq(erpProductUnifiedTakedown.getCollectProductId() != null, ErpProductUnifiedTakedown::getCollectProductId, erpProductUnifiedTakedown.getCollectProductId());
        lqw.eq(erpProductUnifiedTakedown.getAeProductId() != null, ErpProductUnifiedTakedown::getAeProductId, erpProductUnifiedTakedown.getAeProductId());
        lqw.eq(erpProductUnifiedTakedown.getIsEffective() != null, ErpProductUnifiedTakedown::getIsEffective, erpProductUnifiedTakedown.getIsEffective());
        lqw.eq(erpProductUnifiedTakedown.getIsExecute() != null, ErpProductUnifiedTakedown::getIsExecute, erpProductUnifiedTakedown.getIsExecute());
        lqw.eq(erpProductUnifiedTakedown.getType() != null, ErpProductUnifiedTakedown::getType, erpProductUnifiedTakedown.getType());
        List<ErpProductUnifiedTakedownVo> erpProductUnifiedTakedownVos = baseMapper.selectVoList(lqw);
        return R.ok(erpProductUnifiedTakedownVos);
    }

    @Override
    public R<Object> getProductUnifiedTakedownInfo(ErpProductUnifiedTakedown erpProductUnifiedTakedown) {
        LambdaQueryWrapper<ErpProductUnifiedTakedown> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(erpProductUnifiedTakedown.getTakedownReason()), ErpProductUnifiedTakedown::getTakedownReason, erpProductUnifiedTakedown.getTakedownReason());
        lqw.eq(erpProductUnifiedTakedown.getCollectProductId() != null, ErpProductUnifiedTakedown::getCollectProductId, erpProductUnifiedTakedown.getCollectProductId());
        lqw.eq(erpProductUnifiedTakedown.getAeProductId() != null, ErpProductUnifiedTakedown::getAeProductId, erpProductUnifiedTakedown.getAeProductId());
        lqw.eq(erpProductUnifiedTakedown.getIsEffective() != null, ErpProductUnifiedTakedown::getIsEffective, erpProductUnifiedTakedown.getIsEffective());
        lqw.eq(erpProductUnifiedTakedown.getIsExecute() != null, ErpProductUnifiedTakedown::getIsExecute, erpProductUnifiedTakedown.getIsExecute());
        lqw.eq(erpProductUnifiedTakedown.getType() != null, ErpProductUnifiedTakedown::getType, erpProductUnifiedTakedown.getType());
        ErpProductUnifiedTakedown erpProductUnifiedTakedownSel = baseMapper.selectOne(lqw);
        return R.ok(erpProductUnifiedTakedownSel);
    }


}
